package com.github.maojx0630.easy.translate.advice;

import com.github.maojx0630.easy.translate.TranslateUtil;
import com.github.maojx0630.easy.translate.ann.IgnoreTranslate;
import lombok.AllArgsConstructor;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author 毛家兴
 * @since 2024-02-02 11:20
 */
@ControllerAdvice
@AllArgsConstructor
@Order(Integer.MIN_VALUE)
public class TranslateAdvice implements ResponseBodyAdvice<Object> {

  private TranslateUtil translateUtil;

  @Override
  public boolean supports(
      MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> converterType) {
    boolean flag =
        methodParameter.getDeclaringClass().isAnnotationPresent(IgnoreTranslate.class)
            || (methodParameter.getMethod() != null
                && methodParameter.getMethod().isAnnotationPresent(IgnoreTranslate.class));
    return !flag;
  }

  @Override
  public Object beforeBodyWrite(
      Object o,
      MethodParameter returnType,
      MediaType selectedContentType,
      Class<? extends HttpMessageConverter<?>> selectedConverterType,
      ServerHttpRequest request,
      ServerHttpResponse response) {
    return translateUtil.translate(o);
  }
}
